#include "mypthread.hpp"
#include "lockProtect.hpp"
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int amount = 10000;

void *handler(LockAndName *ln)
{
    while (true)
    {
        {
            PrRes ps(ln->_pmutex);
            if (amount > 0)
            {
                usleep(1000);
                std::cout << ln->_name << ", " << amount-- << std::endl;
            }
            else
                break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);

    LockAndName ln1(&mutex);
    Thread<LockAndName *, void *> t(handler, &ln1, ln1._name);

    LockAndName ln2(&mutex);
    Thread<LockAndName *, void *> t2(handler, &ln2, ln2._name);

    LockAndName ln3(&mutex);
    Thread<LockAndName *, void *> t3(handler, &ln3, ln3._name);

    LockAndName ln4(&mutex);
    Thread<LockAndName *, void *> t4(handler, &ln4, ln4._name);

    t.Start(); t2.Start(); t3.Start(); t4.Start();

    t.Join(); t2.Join(); t3.Join(); t4.Join();

    pthread_mutex_destroy(&mutex);
    // pthread_mutex_t mutex;
    // pthread_mutex_init(&mutex, nullptr);
    // Thread<pthread_mutex_t*, void*> t(handler, &mutex);
    // Thread<pthread_mutex_t*, void*> t2(handler, &mutex);
    // Thread<pthread_mutex_t*, void*> t3(handler, &mutex);
    // Thread<pthread_mutex_t*, void*> t4(handler, &mutex);

    // t.Start();
    // t2.Start();
    // t3.Start();
    // t4.Start();

    // t.Join();
    // t2.Join();
    // t3.Join();
    // t4.Join();

    return 0;
}
void Print(Thread<int, int> &t)
{
    std::cout << "thread name : " << t.GetThreadName()
              << ", thread id : " << t.GetTid()
              << ", thread is runnning ? " << t.IsRunning()
              << ", thread retval : " << t.GetRetVal()
              << std::endl;
}
int handler2(int a)
{
    while (a)
    {
        std::cout << "hello I am " << a-- << std::endl;
        sleep(1);
    }
    return 12345678;
}